package com.ruoyi.purchase.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.purchase.domain.Offers;
import com.ruoyi.purchase.mapper.OffersMapper;
import com.ruoyi.purchase.service.IOffersService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;

/**
 * offersService业务层处理
 * 
 * @author hmy
 * @date 2025-08-22
 */
@Service
public class OffersServiceImpl implements IOffersService 
{
    @Autowired
    private OffersMapper offersMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询offers
     * 
     * @param offerId offers主键
     * @return offers
     */
    @Override
    public Offers selectOffersByOfferId(Long offerId)
    {
        return offersMapper.selectOffersByOfferId(offerId);
    }

    /**
     * 查询offers列表
     * 
     * @param offers offers
     * @return offers
     */
    @Override
    public List<Offers> selectOffersList(Offers offers)
    {
        return offersMapper.selectOffersList(offers);
    }

    /**
     * 新增offers
     * 
     * @param offers offers
     * @return 结果
     */
    @Override
    public int insertOffers(Offers offers) {
        // 插入数据
        int result = offersMapper.insertOffers(offers);

//        if (result > 0) {
//            // 发送邮件通知
//            if ("public".equals(offers.getVisibility())) {
//                sendOfferNotificationToAllUsers(offers);
//            }
//        }

        return result;
    }
    /**
     * 获取所有用户的邮箱地址
     * @return 邮箱列表
     */
    private List<String> getAllUserEmails() {
        List<SysUser> users = sysUserMapper.selectUserList(new SysUser()); // 查询所有用户
        return users.stream()
                .filter(user -> StringUtils.isNotBlank(user.getEmail())) // 过滤空邮箱
                .map(SysUser::getEmail)
                .collect(Collectors.toList());
    }

    /**
     * 向所有用户发送 offer 通知邮件
     */
    private void sendOfferNotificationToAllUsers(Offers offers) {
        try {
            List<String> emails = getAllUserEmails();

            if (emails.isEmpty()) {
                System.out.println("没有找到任何用户邮箱，跳过邮件发送");
                return;
            }

            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");

            String from = "203125235@qq.com"; // 发件人邮箱
            helper.setFrom(from);
            helper.setTo(emails.toArray(new String[0])); // 批量收件人
            helper.setSubject("Offer " + offers.getOfferId()+" has been posted");

            StringBuilder htmlContent = new StringBuilder();
            htmlContent .append("<p><strong>Product:</strong> ").append(offers.getOfferName()).append("</p>")
                    .append("<p><strong>Price:</strong> ").append(offers.getPrice()).append("</p>")
                    .append("<p><strong>Quantity:</strong> ").append(offers.getQuantity()).append("</p>");
            if (offers.getExpiresAt() != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                htmlContent.append("<p><strong>Expires:</strong> ").append(sdf.format(offers.getExpiresAt())).append("</p>");
            }

            if (offers.getNote() != null && !offers.getNote().trim().isEmpty()) {
                htmlContent.append("<p><strong>Note:</strong><br/> ").append(offers.getNote().replace("\n", "<br/>")).append("</p>");
            }

            helper.setText(htmlContent.toString(), true);

            javaMailSender.send(mimeMessage);
            System.out.println("✅ 邮件已成功发送给 " + emails.size() + " 位用户：Offer ID=" + offers.getOfferId());
        } catch (Exception e) {
            System.err.println("❌ 邮件发送失败：" + e.getMessage());
            e.printStackTrace();
        }
    }



    /**
     * 修改offers
     * 
     * @param offers offers
     * @return 结果
     */
    @Override
    public int updateOffers(Offers offers) {
        int result = offersMapper.updateOffers(offers);

        if (result > 0) {
            // 只有当 visibility 改为 public 时才发送（避免重复发送）
            if ("public".equals(offers.getVisibility())) {
                sendOfferNotificationToAllUsers(offers);
            }
        }

        return result;
    }


    /**
     * 批量删除offers
     * 
     * @param offerIds 需要删除的offers主键
     * @return 结果
     */
    @Override
    public int deleteOffersByOfferIds(Long[] offerIds)
    {
        return offersMapper.deleteOffersByOfferIds(offerIds);
    }

    /**
     * 删除offers信息
     * 
     * @param offerId offers主键
     * @return 结果
     */
    @Override
    public int deleteOffersByOfferId(Long offerId)
    {
        return offersMapper.deleteOffersByOfferId(offerId);
    }
}
